package soria.cabinet.gui.components.cabinet;

import soria.cabinet.utils.SFile;
import soria.cabinet.utils.SFont;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

//文件树
public class FileTreePosition {
    //Panel
    public static JPanel panel = new JPanel();
    //根节点目录
    private static final File rootDir = new File(new File("").getAbsolutePath()+"/Cabinet");
    //根节点
    private static final DefaultMutableTreeNode root = new DefaultMutableTreeNode(rootDir.getName());
    //树
    private static final JTree tree = new JTree(root);

    private static final JButton flushBtn = new JButton("刷新");

    static {
        panel.setLayout(null);
        panel.setBounds(5, 5, 205, 520);
        panel.setBorder(BorderFactory.createRaisedBevelBorder());
        initial();
    }

    private static void initial(){
        //设置树节点只能单选
        TreeSelectionModel model = tree.getSelectionModel();
        model.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        //树的样式
        tree.setFont(SFont.TEXT);
        tree.setBounds(3, 3, 199, 470);
        tree.addTreeSelectionListener(new TreeActionListener());
        //获取Cabinet目录下所有文件和文件夹
        SFile.viewAll(root, rootDir);
        panel.add(tree);

        flushBtn.setBounds(50,480,100,30);
        flushBtn.setFont(SFont.DEFAULT_CN);
        flushBtn.addActionListener(new FlushListener());
        panel.add(flushBtn);
    }

    //事件监听器：获取树中节点的文件路径
    private static class TreeActionListener implements TreeSelectionListener {
        @Override
        public void valueChanged(TreeSelectionEvent e) {
            DefaultMutableTreeNode node =
                    (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            String name = node.toString();
            if(new File(SFile.getPath(name)).isFile()){
                //将文件的属性预览到右侧窗口
                new FileInfoPosition(name);
            }
        }
    }

    //事件监听器：刷新文件柜
    private static class FlushListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            root.removeAllChildren();
            SFile.viewAll(root,rootDir);
            tree.updateUI();
        }
    }
}
